package cn.cimoc.config.security;

import cn.cimoc.model.JwtUser;
import cn.cimoc.model.po.TRole;
import cn.cimoc.model.po.TUser;
import cn.cimoc.util.SpringUtils;
import cn.cimoc.constant.ConstantPool;
import cn.cimoc.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;


@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    PasswordEncoder myPasswordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TUser user = userMapper.selectOne(
                new QueryWrapper<TUser>()
                        .eq("username", username));
        if (null == user) {
            SpringUtils.getHttpServletRequest().setAttribute(ConstantPool.USER_DOES_NOT_EXIST, "");
            throw new UsernameNotFoundException("");
        } else {
            TRole role = userMapper.findRoleByUsername(username);
            String roleName = ConstantPool.ROLE_PREFIX + role.getName();
            List<GrantedAuthority> list = AuthorityUtils.commaSeparatedStringToAuthorityList(roleName);
            return JwtUser.builder()
                    .id(user.getUid())
                    .username(username)
                    .password(user.getPassword())
                    .authorities(list)
                    .build();
        }
    }
}
